var setting_pass = ""; // 设置密码输入
var templateCode = tool.getUrlParam("templateCode") || "OT2023053111100810210";
var dataTemplate = {};
// 队列 初始化content的事件队列（一般是content注册销毁时需要timer）
var listContentReInit = [];
// 页面返回标志
var isBack = tool.getUrlParam("isBack") || false;

// 是否打开 默认启动方式 对应需求一
var SWITCH_BOOT_PLAY = false;
// 是否打开 20秒自动全屏播 对应需求二
var SWITCH_TIME_PLAY = true;
// 对应需求二 等待时间
var TIME_FOTOFULL = 20 * 1000;

// 非跳转到直播
var notToLive = true;

var isToastSwitch = false;

cmd.set("6192", {
  desc: "清除启动项",
  func: function () {
    store.del("notToLive");
    msg.alert("已清除启动项");
  },
});

var start = function () {
  createFilter();
  createBox();
  bindEvent();

  if (!isBack) {
    if (SWITCH_BOOT_PLAY) {
      notToLive = store.get("notToLive");
    }
    if (notToLive) {
      $("baseView").css("opacity", 1);
    }
  } else {
    $("baseView").css("opacity", 1);
    if (SWITCH_BOOT_PLAY) {
      var backType = store.get("notToLive");
      // 若无值才进行弹窗
      if (backType === null) {
        isToastSwitch = true;
        showSwitchBoot();
      }
    }
  }

  loadData();
};
start();

// 创建过滤器
function createFilter() {
  // 筛选器，推荐位名称是否展示
  filter.set("filterItemText", function (data) {
    if (data.showName == "1") {
      return "";
    } else {
      return "display: none";
    }
  });
  filter.set("filterItemImg", function (data) {
    if (data.pictureUrl) {
      return "";
    } else {
      return "display: none";
    }
  });

  // 筛选器，大推荐位根据类型判断焦点样式
  filter.set("filterFocusType", function (info) {
    if (info == "1") {
      return " video";
    }
    if (info == "4" || info == "6") {
      return " picture";
    }
  });
  // 跑马灯相关过滤器
  filter.set("filterDirection", function (info) {
    var arr = ["left", "left", "right", "up", "down"];
    if (!arr[info]) {
      info = 0;
    }
    return arr[info];
  });
  filter.set("filterFontSize", function (info) {
    return info ? info : 28;
  });
}

function createBox() {
  // 搜索、设置按钮
  box0 = new eZone.BoxInstance(1, 1, [-1, -1, 3, -1], 0);
  // 密码输入窗口
  box1 = new eZone.BoxInstance(3, 4, [-1, -1, 2, -1], 1);
  box2 = new eZone.BoxInstance(1, 2, [1, -1, -1, -1], 2);

  // 内容
  box3 = new eZone.BoxInstance(1, 1, [-1, -1, -1, 4], 3);
  box4 = new eZone.BoxInstance(1, 1, [-1, 3, 5, -1], 4);
  box5 = new eZone.BoxInstance(1, 1, [4, 3, -1, -1], 5);

  // 跑马灯
  box6 = new eZone.BoxInstance(1, 1, [3, -1, -1, -1], 6);

  // 选择启动下
  box7 = new eZone.BoxInstance(1, 2, [-1, -1, -1, -1], 7);

  box0.IOIsRecordArr = [false, false, true, false];

  box1.setMoveArray(-1, -1, "10-2>1,11-2>1", -1);
  box2.setMoveArray("0-1>8,1-1>10", -1, -1, -1);

  box4.IOIsRecordArr = [false, true, false, false];
  Wrapper.init([], 3, 0);
}

function loadData() {
  loadPageData();
  reportPage("index");
}

function getBackUrl() {
  var url = window.location.href;
  if (url.indexOf("?") == -1) {
    url += "?";
  } else {
    url += "&";
  }
  url += "isBack=true";
  return url;
}

function bindEvent() {
  box0.boxOkEvent = function () {
    // 显示数字键盘
    $("view_setting").show();
    Wrapper.changeFocus(1, 0);
  };

  box1.boxOkEvent = function () {
    var next = $("box1_" + this.curIndex).html();
    if (next == "清除") {
      setting_pass = "";
    } else if (next == "删除") {
      setting_pass = setting_pass.substr(0, setting_pass.length - 1);
    } else {
      setting_pass = setting_pass + "" + next;
    }

    if (setting_pass == "") {
      $("setting_text").html("请输入设置密码");
    } else {
      $("setting_text").html(new Array(setting_pass.length + 1).join("*"));
    }
  };

  box2.boxOkEvent = function () {
    if (this.curIndex == 0) {
      if (setting_pass == "9653196531") {
        setting_close();
        setTimeout(function () {
          gotoSetting();
        }, 200);
      } else if (setting_pass == "9527" || cmd.developer) {
        var func = cmd.data[setting_pass] && cmd.data[setting_pass].func;
        if (func) {
          func();
          setting_pass = "";
          $("setting_text").html("请输入设置密码");
        }
      } else {
        $("setting_err").show();
        setTimeout(function () {
          $("setting_err").hide();
        }, 2000);
      }
    } else {
      setting_close();
    }
  };

  box7.boxOkEvent = function () {
    store.set("notToLive", this.curIndex == 1);
    $("view_selectBoot").hide();
    Wrapper.changeFocus(3, 0);
    isToastSwitch = false;
    startWindowPlay(box3.data[0]);
    initTimerGoToFull();
  };

  box3.boxOkEvent =
    box4.boxOkEvent =
    box5.boxOkEvent =
      function () {
        clickRecom(this);
      };

  function clickRecom(box) {
    var _data = box.data[box.curIndex];
    var columnData = box.columnData;

    if (_data.content.status === 0) {
      msg.alert("该内容已下线");
      return;
    }
    reportRecom(_data, columnData);
    Wrapper.keyPressLock = true;
    if (_data.typeCode === "1") {
      // 直播
      var url = "";
      if (_data.name.indexOf("回看") != -1) {
        url = "http://111.11.189.150:8080/CMCC2/page/playback/playbackList.jsp?";
      } else {
        url = "http://111.11.189.151:8080/CMCC2/page/channelplayer/player.jsp?";
        // 写死的参数
        url += "categoryCode=1484&channelIndex=1&channelID=579&";
        url += "playurl=" + escape(_data.content.timeshiftUrl);
        url += "&";
      }
      reportPage("live");
      reportContent();
      // 销毁小窗播放
      playerWindow.destory();

      isPlayState = false;
      nativeClient.openLive();

      // var returnurl = escape(getBackUrl());
      // url += "returnurl=" + returnurl;

      // // listionPageBack();
      // clearTimeout(timerGoToFull);

      // if (_data.name.indexOf("回看") != -1) {
      //   loadUrl(url, {}, false);
      // } else {
      //   try {
      //     Utility.startPlayActivity(url);
      //   } catch (e) {
      //     loadUrl(url, {}, false);
      //   }
      // }
    }
    if (_data.typeCode === "4") {
      // 图文
      // 销毁小窗播放
      playerWindow.destory();
      isPlayState = false;
      var url = "/hotel_page/page/frame.html?code=" + _data.contentCode + "&templateCode=" + templateCode + "&backUrl=" + encodeURIComponent(getBackUrl());
      loadUrl(url);
    }
    if (_data.typeCode === "5") {
      // 点播
      playFullScreen(_data);
      return;
    }
    if (_data.typeCode === "6") {
      // 轮播
      // 销毁小窗播放
      playerWindow.destory();
      isPlayState = false;
      var url = "/hotel_page/page/picture.html?code=" + _data.contentCode + "&backUrl=" + encodeURIComponent(getBackUrl());
      loadUrl(url);
    }
    Wrapper.keyPressLock = false;
  }

  Wrapper.backEvent = function () {
    Wrapper.backFlag = true;
    if (Wrapper.curBoxId == 1 || Wrapper.curBoxId == 2) {
      setting_close();
      Wrapper.backFlag = false;
    } else if (Wrapper.curBoxId == 7) {
      Wrapper.backFlag = false;
    }
  };
}

// 显示选择启动项界面
function showSwitchBoot() {
  Wrapper.changeFocus(7, 0);
  $("view_selectBoot").show();
}

// 全屏播放
function playFullScreen(_data) {
  var url = location.href.replace(/page\/(.*)/, "page/play.html?random=" + Math.random());

  var url = location.href.replace(/page\/(.*)/, "player/player.html?random=" + Math.random());
  store.set("playUrl", _data.content.videoUrl);

  url += "&url=" + encodeURIComponent(_data.content.videoUrl);
  url += "&progName=" + escape(_data.content.name);
  url += "&code=" + _data.contentCode;

  // listionPageBack();

  isPlayState = false;
  playerWindow.destory().fullScreen(url);
}

// 定时器到全屏功能
var timerGoToFull = null;
// 重置定时到全屏播放
function initTimerGoToFull() {
  if (!SWITCH_TIME_PLAY) {
    return;
  }
  if (timerGoToFull) {
    clearTimeout(timerGoToFull);
  }
  if ([1, 5].indexOf(+box3.data[0].typeCode) == -1) {
    return;
  }

  // msg.alert('|st|', true);

  timerGoToFull = setTimeout(function () {
    // msg.alert('|find|', true);
    clearTimeout(timerGoToFull);
    timerGoToFull = null;
    box3.boxOkEvent();
  }, TIME_FOTOFULL);
}

function showUserInfo() {
  alertMsg(JSON.stringify(user.userInfo), true);
  alertMsg("----userID：" + user.userID + "<br/>", true);
  alertMsg("----stbID：" + user.stbID + "<br/>", true);
  alertMsg("----mac：" + user.mac + "<br/>", true);
  alertMsg("----stbType：" + user.stbType + "<br/>", true);
  alertMsg("----userGroup：" + user.userGroup + "<br/>", true);
  alertMsg("----areaCode：" + user.areaCode + "<br/>", true);
  alertMsg("----countryCode：" + user.countryCode + "<br/>", true);
  alertMsg("----cityCode：" + user.cityCode + "<br/>", true);
}

/**
 * 关闭密码输入窗口
 */
function setting_close() {
  setting_pass = "";
  $("setting_text").html("请输入设置密码");
  $("view_setting").hide();
  Wrapper.changeFocus(0, 0);
}

/**
 * 跳转到设置 预留
 */
function gotoSetting() {
  //跳转到设置预留
  if (typeof Utility != "undefined" && Utility.openNetSettings) {
    Utility.openNetSettings();
  } else if (typeof nativeClient != "undefined" && nativeClient.openNetSettings) {
    nativeClient.openNetSettings();
  }
}

/**
 * 加载页面数据
 */
function loadPageData() {
  var resultCommonTodo = function () {
    // 渲染顶部信息
    renderHeader();
    // 渲染模板
    renderContent();
    // 渲染跑马灯
    renderFooter();
  };
  http.get({
    url: "/hoteltemplateepg/template/epg/templateInfo/{templateCode}",
    params: { templateCode: templateCode },
    success: function (res) {
      if (res.code == 200 && Object.getOwnPropertyNames(res.data).length) {
        dataTemplate = res.data;
        //本地化存储
        store.set("dataTemplate", dataTemplate);
        resultCommonTodo();
      }
    },
    error: function (res) {
      dataTemplate = store.get("dataTemplate") || {};
      if (Object.getOwnPropertyNames(dataTemplate).length) {
        resultCommonTodo();
      }
    },
  });
}

// 渲染模板
function renderContent() {
  // 背景图片
  var bgImg = dataTemplate.backgroundUrl ? filter.getPicture(dataTemplate.backgroundUrl) : "../img/index/bg.png";
  loadImage("bg", bgImg);
  // logo
  var logoImg = dataTemplate.logoUrl ? filter.getPicture(dataTemplate.logoUrl) : "../img/index/logo.png";
  loadImage("hotel_logo", logoImg);

  // 封装获取栏目数据
  var getContentData = function (code, callback) {
    http.get({
      url: "/hoteltemplateepg/template/epg/tIptvMerchantCategory/{code}",
      params: {
        code: code,
      },
      success: function (res) {
        callback && callback(res.data);
      },
      error: function () {
        callback && callback(null);
      },
    });
  };

  // 处理左侧数据
  var buildLeft = function (callback) {
    box3.columnData = dataTemplate.categoryList[0];
    getContentData(box3.columnData.code, function (data) {
      if (data) {
        store.set("recomDataLeft", data);
      } else {
        data = store.get("recomDataLeft");
      }
      if ([1, 5].indexOf(+data[0].typeCode) != -1) {
        view.bindDataView(box3, data.slice(0, 1), "templateContentCell", "viewLeft");
        if (notToLive) {
          // 调用小窗播放的方法
          startWindowPlay(data[0]);
          initTimerGoToFull();
        } else {
          // 开始播放
          box3.boxOkEvent();
          return;
        }
      } else {
        var html = buildRecomSwiper({
          id: 3,
          data: data,
        });
        $("viewLeft").html(html);
        box3.initSwiper();
      }
      callback && callback();
    });
  };

  // 处理右侧数据
  var buildRight = function (callback) {
    box4.columnData = box5.columnData = dataTemplate.categoryList[1];
    getContentData(box4.columnData.code, function (data) {
      if (data) {
        store.set("recomDataRight", data);
      } else {
        data = store.get("recomDataRight");
      }

      var dataRight1 = data.slice(0, 1);
      var dataRight2 = data.slice(1);

      var htmls = [];
      var right1 = view.bindDataView(box4, dataRight1, "templateContentCell", "yqling");
      htmls.push(right1);
      var right2 = buildRecomSwiper({
        id: 5,
        data: dataRight2,
      });
      htmls.push(right2);
      $("viewRight").html(htmls.join(""));
      box5.initSwiper();
      callback && callback();
    });
  };

  // 渲染完成后的处理
  var buildContentEnd = function () {
    $("loading").hide();
    Wrapper.changeFocus(Wrapper.curBoxId, Wrapper.indexId);

    initTimerGoToFull();
  };

  buildLeft(function () {
    buildRight(buildContentEnd);
  });
}

/**
 * 渲染跑马灯
 */
function renderFooter() {
  if (dataTemplate.marquee && dataTemplate.marquee.state == 1) {
    // 开始时间
    var startTime = new Date(dataTemplate.marquee.startTime).getTime();
    // 结束时间
    var endTime = new Date(dataTemplate.marquee.endTime).getTime();
    // 当前时间
    var curtime = new Date().getTime();
    if (startTime < curtime && curtime < endTime) {
      var arr = [dataTemplate.marquee];
      view.bindDataView(box6, arr, "templateMarquee", "marquee_cursor");
      $("footer").show();
    } else {
      $("footer").hide();
    }
  } else {
    $("footer").hide();
  }
}

/**
 * 加载其他信息数据
 * @returns
 */
function renderHeader() {
  var weekStr = "天一二三四五六";
  var setTime = function () {
    var t = getDateVal();
    var text = t.month + "/" + t.day + " &nbsp 星期" + weekStr[t.weekDay] + " &nbsp " + t.hour + ":" + t.minute;
    $("info_date").html(text);
    // $("customerName").html(dataTemplate.customerName);
  };
  setInterval(setTime, 5000);
  setTime();
  $("info").show();
}

function loadImage(domId, url) {
  $(domId).css("opacity", "0");
  $(domId).css("backgroundImage", "url(" + url + ")");
  $(domId).css("display", "block");
  setTimeout(function () {
    $(domId).css("opacity", "1");
  }, 300);
}

// 生成推荐位内的轮播图 可以封装到单独文件
function buildRecomSwiper(options) {
  // 保留设置默认的数据
  var defaultOptions = {
    templateRecom: "templateSwiperRecom",
    templateRecomItem: "templateSwiperRecomItem",
    onceTime: 5000,
  };
  var box = Wrapper.boxes[options.id];
  var options = tool.objectAssign({}, defaultOptions, options);
  // 获取最终html
  var htmls = view.getTemplateHtmls(options.templateRecom, [
    {
      id: options.id,
      // 获取内层实际轮播html 并给box:重置ele和设置data
      swiper: view.bindDataView(options.id, options.data, options.templateRecomItem, "yqling"),
    },
  ]);

  // 修复轮播序号
  var fixSwiperIndex = function (offset) {
    var next = box.swiperIndex + offset;
    if (next < 0) {
      next = box.totalEle - 1;
    } else if (next > box.totalEle - 1) {
      next = 0;
    }
    var domNow = $("box" + box.id + "_swiper" + box.swiperIndex);
    domNow.removeClass("focus");
    var domNext = $("box" + box.id + "_swiper" + next);
    domNext.addClass("focus");
    box.swiperIndex = next;
  };
  // 初始化轮播序号
  box.swiperIndex = 0;
  // 页面渲染后记得及时调用init，或改写为一次性定时器init
  box.initSwiper = function () {
    // 清除timer 避免多次创建
    clearInterval(box.timer);
    fixSwiperIndex(0);
    box.timer = setInterval(function () {
      fixSwiperIndex(1);
    }, options.onceTime);
  };
  // 清除轮播定时器
  box.destorySwiper = function () {
    console.log("清除box" + box.id + "的swiper定时器");
    clearInterval(box.timer);
  };
  // 注册销毁机制
  listContentReInit.push(box.destorySwiper);
  // 返回轮播图html
  return htmls;
}

// 创建监听页面返回（安卓activity配合store）
// function listionPageBack() {
//   clearInterval(window.timerPageBack);
//   setTimeout(function () {
//     window.timesNumb = 0;
//     window.timerPageBack = setInterval(function () {
//       // 标志
//       var isBack = 0;
//       // 方法1
//       if (!document.webkitHidden) {
//         isBack = 1;
//       }

//       // msg.alert(isBack, true);

//       // 方法2  播放器activity不支持localStorage弃用
//       // var info = store.get("backInfoTag");
//       // if (info == 1) {
//       //   isBack = 2;
//       //   store.del("backInfoTag");
//       // }
//       if (isBack) {
//         // msg.alert('|回显|', true);
//         clearInterval(window.timerPageBack);

//         var backType = store.get("notToLive");
//         if (SWITCH_BOOT_PLAY && backType === null) {
//           // 若无值才进行弹窗
//           isToastSwitch = true;
//           showSwitchBoot();
//         } else {
//           startWindowPlay(box3.data[0]);
//           initTimerGoToFull();
//         }

//       } else {
//         // msg.toast("" + window.timesNumb, true, true);
//       }
//     }, 100);
//   }, 100);
// }

var saveData = null;
var isPlayState = false;
// 开始小窗播放
function startWindowPlay(data) {
  if (isToastSwitch) {
    return;
  }
  if (isPlayState) {
    return;
  }
  isPlayState = true;
  if (!data) {
    data = saveData;
  }
  saveData = data;
  var url = "";
  if (data.typeCode == 1) {
    // 直播
    url = data.content.timeshiftUrl;
    // url = "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"
  } else if (data.typeCode == 5) {
    // 点播
    url = data.content.videoUrl;
  }

  // msg.alert('|起播|', true);
  var scaling = getSmallPlayViewScaling();
  if (url) {
    playerWindow.create({
      url: url,
      left: 109 / scaling,
      top: 218 / scaling,
      width: 1118 / scaling,
      height: 636 / scaling,
    });
  }
}

function videoResumeEvent() {
  startWindowPlay();
}

function getSmallPlayViewScaling() {
  // if (user.userID == "TV9313694729" || user.userID == "TV9371456480" || user.userID == "TV9373979130") {
  //   msg.alert("----盒子型号：" + user.stbType + "----缩放比例：" + window.devicePixelRatio, true);
  // }
  if (user.stbType.indexOf("H10g-12") > -1 || user.stbType.indexOf("H10g-13") > -1) {
    return 1;
  } else {
    return 1.5;
  }
}
